﻿var form, element, upload, layer, table;
layui.use(['form', 'upload', 'element', 'layer', 'table'], function () {
    form = layui.form;
    upload = layui.upload;
    element = layui.element;
    layer = layui.layer;
    table = layui.table;
    //切换选项卡
    element.on('tab(topTab)', function (data) {
        debugger
        var id = $(data.elem[0]).find(".layui-this").attr("lay-id");
        $(".layui-tab-content").removeClass("lay-show");
        $(".layui-tab-content[data-id='" + id + "']").addClass("lay-show");

        $(".layui-nav-child dd").removeClass("layui-this");
        $(".layui-nav-child dd[data-id='" + id + "']").addClass("layui-this");
    });

    //删除选项卡
    $(".layui-tab").on("click", function (e) {
        if ($(e.target).is(".layui-tab-close")) {
            toDelete($(e.target).parent().attr("lay-id"));
        }
    })

    //添加选项卡
    $(".layui-nav-child dd").click(function () {
        var id = $(this).data("id");
        var url = $(this).data("url");
        var title = $(this).data("title");
        var title1 = $(this).data("title1");
        $("#pageName1").removeAttr("style").text(title1);
        $("#pageName2").removeAttr("style").text(title);
        debugger
        var tab = $("#topTab").find("[lay-id='" + id + "']");
        if (!id && id != 0 && id != "0") {
            return;
        }

        //切换到选项卡
        if (tab.length > 0) {
            toChange(id);
        }
        //新增选项卡
        else {
            tabAdd(id, title, url);
            toChange(id);
        }
    });

    //添加选项卡(userpc)
    $(".layui-nav-item-leftnav a").click(function () {
        var id = $(this).data("id");
        var url = $(this).data("url");
        var title = $(this).data("title");
        var tab = $("#topTab").find("[lay-id='" + id + "']");
        if (!id && id != 0 && id != "0") {
            return;
        }

        //切换到选项卡
        if (tab.length > 0) {
            toChange(id);
        }
        //新增选项卡
        else {
            tabAdd(id, title, url);
            toChange(id);
        }
    });


    function tabAdd(id, title, url) {
        //新增一个Tab项
        element.tabAdd('topTab', {
            title: title,
            id: id
        });
        $(".layui-tab-content").removeClass("lay-show");
        $("#layui-body").append('  <div class="layui-tab-content lay-show" data-id="' + id + '">  <iframe src="' + url + '"></iframe> </div>');
    }

    function toDelete(id) {
        $(".layui-tab-content[data-id='" + id + "']").remove();
    }

    function toChange(id) {
        element.tabChange('topTab', id);
    }

});


function changePageName1(name) {
    $("#pageName1").removeAttr("style").text(name);
    $("#pageName2").attr("style", "display:none").text("");
}

var beforeLoad;
/**
 * ajax请求动画
 * */
function ajaxLoadding() {
    beforeLoad = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });
}

/**  
 * 关闭ajax请求动画
 * */
function closeAjaxLoadding() {
    layer.close(beforeLoad);
}

/**
 * 关闭所有的弹窗
 * */
function closeLayer() {
    layer.closeAll();
}

/**
 *  普通提示信息
 */
function showMessage(msg) {
    layer.msg(msg, { time: 3000 });
}

/**
 *  操作成功提示框,有回调
 */
function showMessageCallBack(msg, callBack) {
    var index = layer.alert(msg, {
        icon: 1, time: 3000, offset: 't', closeBtn: 0, title: '操作成功', btn: [], anim: 0, shade: 0,
        end: function () {
            if (callBack) {
                callBack();
            }
        }
    });
    layer.style(index, {
        color: '#777',
        top: '250px'
    });
}


/**
 * 弹出错误信息 
 */
function showError(msg, e) {
    if (e) {
        console.dir(e);
    }
    var index = layer.alert(msg, { icon: 2, time: 3000, offset: 't', closeBtn: 0, title: '错误信息', btn: [], anim: 6, shade: 0 });
    layer.style(index, {
        color: '#777',
        top: '250px'
    });
}


/**
 * 通用上传功能 
 */
function FileUploadInit(btnId, type, size, url, isMultiple, before, success) {
    var accept, acceptMime, exts, uploadFiles;
    switch (type) {
        case "1"://图片上传
            accept = "images";
            acceptMime = "image/jpg,image/png,image/gif,image/jpeg";
            exts = "jpg|png|gif|jpeg";
            break;
        case "2"://excel上传
            accept = "file";
            acceptMime = "application/vnd.ms-excel,application/msword";
            exts = "xls|xlsx|doc|docx";
            break;
        default:
            accept = "file";
            break;
    }
    return upload.render({
        elem: '#' + btnId,
        url: url,
        size: size,
        accept: accept,
        acceptMime: acceptMime,
        exts: exts,
        before: function (obj) {
            var that = this;
            uploadFiles = obj.pushFile();
            before(obj, that);
        },
        multiple: isMultiple,
        done: function (res) {
            for (var p in uploadFiles) {
                delete uploadFiles[p];
            }
            //如果上传失败
            if (res.code == 0) {
                showError(res.msg);
                return false;
            } else {
                success(res);
            }
        },
        error: function (e) {
            for (var p in uploadFiles) {
                delete uploadFiles[p];
            }
            showError("上传失败");
        }
    });
}

/**
 * 弹出警告信息
 */
function showWarning(msg) {
    var index = layer.alert(msg, { icon: 3, time: 3000, offset: 't', closeBtn: 0, title: '警告信息', btn: [], anim: 2, shade: 0 });
    layer.style(index, {
        color: '#777',
        top: '50%',
        transform: "translateY(-50%)"
    });
}

/**
 * 弹出操作成功的新
 */
function showSuccess(msg) {
    var index = layer.alert(msg, { icon: 1, time: 2000, closeBtn: 0, title: '提示', btn: [], anim: 1, shade: 0 });
    layer.style(index, {
        color: '#777',
        top: '50%',
        transform: "translateY(-50%)",
        height: '115px'
    });
}


/**
 * ajax请求统一回调 
 */
function ajaxResultBack(res, callBack) {

    if (res.IsSuccess) {
        if (callBack) {
            callBack();
        }
    } else {
        if (res.ResultType == "1") {
            showError(res.Message);
        }
        else if (res.ResultType == "2") {
            showWarning(res.Message);
        }
    }
}

/**
 * 验证时间
 * @param {any} 开始时间
 * @param {any} 结束时间
 * @param {any} 回调函数
 */

function checkDate(start, end, callBack) {
    var startTime = new Date(start);
    var endTime = new Date(end);
    if (startTime > endTime) {
        dateChecked = false;
        layer.msg("开始日期不得大于结束日期", { icon: 0 });
        return;
    }
    if (callBack) {
        callBack();
    }
}

var code = "";
/**
 *  生成验证码
 */
function createCode(e) {
    code = "";
    var codeLength = 4;
    var selectChar = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    for (var i = 0; i < codeLength; i++) {
        var charIndex = Math.floor(Math.random() * 60);
        code += selectChar[charIndex];
    }
    if (code.length != codeLength) {
        createCode(e);
    }
    if (canGetCookie == 1) {
        setCookie(e, code, 60 * 60 * 60, '/');
    } else {
        return code;
    }
}


//hours为空字符串时,cookie的生存期至浏览器会话结束。  
//hours为数字0时,建立的是一个失效的cookie,  
//这个cookie会覆盖已经建立过的同名、同path的cookie（如果这个cookie存在）。 

/**
 * 设置cookie
 */
function setCookie(name, value, hours, path) {
    var name = escape(name);
    var value = escape(value);
    var expires = new Date();
    expires.setTime(expires.getTime() + hours * 3600000);
    path = path == "" ? "" : ";path=" + path;
    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();
    document.cookie = name + "=" + value + _expires + path;
}
/**
 * 获取cookie
 */
function getCookieValue(name) {
    var name = escape(name);
    //读cookie属性，这将返回文档的所有cookie     
    var allcookies = document.cookie;
    //查找名为name的cookie的开始位置     
    name += "=";
    var pos = allcookies.indexOf(name);
    //如果找到了具有该名字的cookie，那么提取并使用它的值     
    if (pos != -1) {    //如果pos值为-1则说明搜索"version="失败     
        var start = pos + name.length;   //cookie值开始的位置     
        var end = allcookies.indexOf(";", start); //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置     
        if (end == -1) end = allcookies.length; //如果end值为-1说明cookie列表里只有一个cookie     
        var value = allcookies.substring(start, end);  //提取cookie的值     
        return unescape(value);       //对它解码           
    }
    else return "-1";    //搜索失败，返回-1  
}

/**
 * 验证树状表格是否选择数据
 */
function checkChoiceTreeTable(treeTable) {
    var data = treeTable.checkStatus();
    if (data.length == 0) {
        showWarning("请选择数据行");
        return false;
    }
    if (data.length > 1) {
        showWarning("当前操作只支持单行");
        return false;
    }
    return data;
}

/**
 * 验证layui表格是否选择数据 
 * table 是layui.table，而不是生成的那个table
 */
function checkChoiceTable(table, tabId, isMore) {
    var data = table.checkStatus(tabId).data;
    if (data.length == 0) {
        showWarning("请选择数据行");
        return false;
    }
    if (!isMore && data.length > 1) {
        showWarning("当前操作只支持单行");
        return false;
    }
    return data;
}

/**
 * 弹出确认提示框
 * */
function showSureMessage(msg, callBack) {
    return layer.confirm(msg, {
        btn: ['确定', '取消'] //按钮
    }, function () {
        callBack();
    }, function () {

    });
}

/**
 *  弹出iframe
 */
function showIframe(url, title, callBack) {
    return layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.3,
        area: ['95%', '95%'],
        content: url,
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);
            var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();比如iframeWin.alert11();
            if (callBack) {
                callBack(iframeWin);
            }
        }
    });
}

function showIframe2(url, title) {
    return layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.3,
        area: ['80%', '85%'],
        content: url
    });
}
function showIframe3(url, title) {
    return layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.3,
        area: ['770px', '700px'],
        content: url
    });
}

/**
 * 重新加载表格
 */
function reloadTable(table, filter) {
    //这个table是渲染的table不是layui.table
    table.reload({
        where: {
            filter: filter,
        },
        page: {
            curr: 1 //重新从第 1 页开始
        }
    })
}

/**
 * 登录掉线（在NoAuth页面调用）
 */
function NoAuth(url, msg) {
    layer.alert(msg, {
        icon: 2, time: 3000, offset: 't', closeBtn: 0,
        title: '错误信息', btn: [], anim: 1, shade: 0, end: function () {
            if (url) {
                // top.location.href = url;
            }
        }
    });
}

/*
 * 统一删除文件的请求
 * data是文件路径的集合
 * */
function DeleteFileList(data, callBack) {

    if (data.length == 0) {
        showWarning("未选中任何文件");
        return false;
    }

    $.ajax({
        type: "post",
        dataType: "json",
        url: "/Upload/DeleteFileList",
        beforeSend: function () {
            ajaxLoadding();
        },
        data: { fileUrls: data },
        success: function (res) {
            showSuccess(res.Message);
            if (res.IsSuccess && callBack) {
                callBack();
            }

        },
        error: function (e) {
            showError("网络或服务器故障<br/>操作失败", e);
        },
        complete: function () {
            closeAjaxLoadding();
        }
    });
}



/**
 * 删除单个文件
 * @param {any} url
 * @param {any} callBack
 */
function DeleteFileOne(url, callBack) {

    $.ajax({
        type: "get",
        dataType: "json",
        url: "/Upload/DeleteFile",
        beforeSend: function () {
            ajaxLoadding();
        },
        data: { url: url },
        success: function (res) {
            showSuccess(res.Message);
            if (res.IsSuccess && callBack) {
                callBack();
            }
        },
        error: function (e) {
            showError("网络或服务器故障<br/>操作失败", e);
        },
        complete: function () {
            closeAjaxLoadding();
        }
    });
}


/**
 * 弹出确认提示框
 * */
function showConfirm(text, success) {
    layer.confirm(text, {
        btn: ['取消', '确定'] //按钮
    }, function () {
        //点击了取消
    }, function () {
        success();
    });

}